package com.yunxin.core.domain.service.order.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.yunxin.core.application.admin.team.Team;
import com.yunxin.core.application.admin.team.TeamTaskDistribute;
import com.yunxin.core.application.dto.user.SysUser;
import com.yunxin.core.domain.model.order.OrderUserApplyAllocation;
import com.yunxin.core.infra.persistence.mapper.order.OrderTeamTaskDetailMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FirstAllocationStatistics {

    private final OrderTeamTaskDetailMapper teamTaskDetailMapper;

    /**
     * 首次分发统计计数
     * @param orderDto
     */
    @Async("threadPoolTaskExecutor")
    public void allocationStatistics(OrderUserApplyAllocation orderDto) {
        try {
            DateTime startTime = DateUtil.beginOfDay(new Date());
            DateTime endTime = DateUtil.endOfDay(new Date());
            DateTime now = DateUtil.date();
            //查询子账户信息和团队信息
            SysUser userDto = teamTaskDetailMapper.findUserIdByAccountId(orderDto.getCurrentAccountId());
            List<Team> teams = teamTaskDetailMapper.findTeamByAccount(orderDto.getCurrentAccountId());
            Team team = teams.get(0);
            //查询当天是否已经存在统计表
            List<TeamTaskDistribute> teamTaskDistribute = teamTaskDetailMapper.selectTeamCountByTime(startTime, endTime, Arrays.asList(userDto.getId()));
            if (teamTaskDistribute.isEmpty()) {
                //为空新建统计
                teamTaskDetailMapper.insertIntoForCount(userDto.getId(), userDto.getNickname(), (long) team.getId(), team.getTeamName(), 1, now);
            } else {
                //当天已有分配记录，更新
                teamTaskDetailMapper.updateForCount(userDto.getId(),(long) team.getId(), team.getTeamName(), 1, teamTaskDistribute.get(0).getCreatTime());
            }
        } catch (Exception e) {
            log.info("首次分发统计异常={}",e);
        }
    }
}
